package com.techfansy.utils;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;

public class PermissionUtils {
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 1;
    private PermissionUtils.RequestPermissionListener requestPermissionListener;

    public PermissionUtils() {
    }

    public void setRequestPermissionListener(PermissionUtils.RequestPermissionListener requestPermissionListener) {
        this.requestPermissionListener = requestPermissionListener;
    }

    public boolean setPermissionUtils(Activity context, String[] permission, int resultCode, PermissionUtils.RequestPermissionListener requestPermissionListener) {
        if (requestPermissionListener != null) {
            this.requestPermissionListener = requestPermissionListener;
        }

        if (Build.VERSION.SDK_INT < 23) {
            if (requestPermissionListener != null) {
                this.requestPermissionListener.permission(resultCode);
            }

            return true;
        } else {
            boolean isPermission = false;

            for(int i = 0; i < permission.length; ++i) {
                if (ContextCompat.checkSelfPermission(context, permission[i]) != 0) {
                    isPermission = true;
                    break;
                }
            }

            if (isPermission) {
                context.requestPermissions(permission, 1);
                return false;
            } else {
                if (requestPermissionListener != null) {
                    this.requestPermissionListener.permission(resultCode);
                }

                return true;
            }
        }
    }

    public void setRequestCode(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (this.requestPermissionListener != null && grantResults.length > 0) {
            this.requestPermissionListener.permission(requestCode);
        }

    }

    public interface RequestPermissionListener {
        void permission(int var1);
    }
}